/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function(mui, jQuery,owner) {
	
    owner.arealist = [
        {name:"新A",value:"新A"},
        {name:"新B",value:"新B"},
        {name:"新C",value:"新C"},
        {name:"新D",value:"新D"},
        {name:"新E",value:"新E"},
        {name:"新F",value:"新F"},
        {name:"新G",value:"新G"},
        {name:"新H",value:"新H"},
        {name:"新J",value:"新J"},
        {name:"新K",value:"新K"},
        {name:"新L",value:"新L"},
        {name:"新M",value:"新M"},
        {name:"新N",value:"新N"},
        {name:"新P",value:"新P"},
        {name:"新Q",value:"新Q"},
        {name:"新R",value:"新R"},
        {name:"外省",value:""}
    ];

    owner.SERVER_URL = "http://47.93.51.73:8080/insuranceLink";
//  owner.SERVER_URL = "http://192.168.2.101:8080/frame";
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		var _self = this;
		console.log("调用到方法----------------------------------");  
		callback = callback || mui.noop;
		loginInfo = loginInfo || {};
		loginInfo.LOGIN_NAME = loginInfo.LOGIN_NAME || '';
		loginInfo.LOGIN_PASS = loginInfo.LOGIN_PASS || '';
		if (loginInfo.LOGIN_NAME == "") {
			return callback('账号不能为空');
		}
		if (loginInfo.LOGIN_PASS == "") { 
			return callback('密码不能为空');
		}
		var loginUrl = _self.SERVER_URL + "/mobilelogin";
		jQuery.ajax(loginUrl,{
						data: JSON.stringify({
							'LOGIN_NAME': loginInfo.LOGIN_NAME, 
							'LOGIN_PASS': loginInfo.LOGIN_PASS,
							'IMEI'      : loginInfo.IMEI
						}),						
						contentType: "application/json",
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							var resultCode = data.RESULT_CODE;
							if (resultCode == '0'){
								var user = {};
								user.LOGIN_NAME = data.LOGIN_NAME;
								user.TOKEN      = data.TOKEN;
								user.USER_NAME      = data.USER_NAME;
								user.COOP_CODE      = data.COOP_CODE;
								user.EMAIL      = data.EMAIL;
								user.MOBILE_PHONE      = data.MOBILE_PHONE;
								user.CONTACT_PHONE      = data.CONTACT_PHONE;
								user.REMARK      = data.REMARK;
								user.FLAG      = data.FLAG;
								user.COOP_NAME      = data.COOP_NAME;
								_self.saveLogin(user)

								var listWebView = plus.webview.getWebviewById('html/case/list.html');
								if(listWebView){
									mui.fire(listWebView,'onLogin',{});
								}
								
								var chatListWebView = plus.webview.getWebviewById('html/case/chat_list.html');
								if(chatListWebView){
									mui.fire(chatListWebView,'onLogin',{});
								}


								return callback();
							}else{
								console.log(resultCode);
								return callback('用户名或密码错误');
							}
						},
						error:function(xhr,type,errorThrown){  
							//异常处理；  
							console.log(type); 
							return callback('登录异常，请重试！错误详情：'+type);
						}
					});
	   
	}; 
	
	//检测当前用户的登录状态
	owner.checkLogin = function(){
		var _self = this;
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		if(user && user.TOKEN){
			plus.nativeUI.showWaiting( "加载中..." );
			var checkTokenUrl = _self.SERVER_URL + "/appApi/checkToken";
			
			$.ajax(checkTokenUrl,{
						data: {
							'LOGIN_NAME': user.LOGIN_NAME, 
							"TOKEN":user.TOKEN
						},
						dataType:'text',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(data);
							plus.nativeUI.closeWaiting();
							var respData = JSON.parse(data); 
							
							if (respData.result_code == '0'){
								var listWebView = plus.webview.getWebviewById('html/case/list.html');
								/*var all = plus.webview.all();
								console.log(all.length);
								var current = plus.webview.currentWebview().id; 
								for(var i=0;i<=all.length -1 ; i++ ){ 
								        console.log(all[i].id);
								    
								} */
								if(listWebView){
									mui.fire(listWebView,'onLogin',{});
								}
								
								var chatListWebView = plus.webview.getWebviewById('html/case/chat_list.html');
								if(chatListWebView){
									mui.fire(chatListWebView,'onLogin',{});
								}
								return user;
							}else{
								_self.toLogin();
							}
						},
						error:function(xhr,type,errorThrown){  
							plus.nativeUI.closeWaiting();
							_self.toLogin();
							//异常处理；  
							console.log(type); 
						
						}
					});
			
		}else {
			_self.toLogin();
		}
		
	};
	
	
	owner.toLogin = function() { 

		mui.openWindow({ 
			id: '/login.html',
			url:'/login.html',
			show: {
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	};
	
	
	owner.addCase = function(caseInfo,callback){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		var _self = this;
		if(user &&user.TOKEN)
		{
			plus.nativeUI.showWaiting( "加载中..." );
			
			var addCaseUrl = _self.SERVER_URL + "/appApi/case/add";
			console.log(user.TOKEN +"----" + user.LOGIN_NAME);
			
			jQuery.ajax(addCaseUrl,{
						data: {
							"TOKEN":user.TOKEN,
							"LOGIN_NAME":user.LOGIN_NAME,
							"CASE_CODE":caseInfo.CASE_CODE,
							"AUTO_NO"  :caseInfo.AUTO_NO
							
						},
						contentType:'application/x-www-form-urlencoded',
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(data);
							plus.nativeUI.closeWaiting();
//							var respData = JSON.parse(text); 
							console.log(data.result_code);
							if(data.result_code == -99 || data.result_code == -98){
								console.log
								_self.toLogin();
							}
							else {
								callback(data);
							}

							
						},
						error:function(xhr,type,errorThrown){  
							plus.nativeUI.closeWaiting();
							 mui.toast('网络异常');
							console.log(errorThrown); 
						
						}
					});
			
		}
		else {
			_self.toLogin();
		}
		
		
	};
	
	
	owner.getCaseDetail = function(caseCode,callback){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		var _self = this;
		if(user &&user.TOKEN)
		{
			plus.nativeUI.showWaiting( "加载中..." );
			
			var caseDetailUrl = _self.SERVER_URL + "/appApi/case/detail";
			console.log(user.TOKEN +"----" + user.LOGIN_NAME);
			
			jQuery.ajax(caseDetailUrl,{
						data: {
							"TOKEN":user.TOKEN,
							"LOGIN_NAME":user.LOGIN_NAME,
					
							"CASE_CODE":caseCode,
							
						},
						contentType:'application/x-www-form-urlencoded',
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(data);
							plus.nativeUI.closeWaiting();
//							var respData = JSON.parse(text); 
							callback(data);
							
						},
						error:function(xhr,type,errorThrown){  
							plus.nativeUI.closeWaiting();
							 mui.toast('网络异常');
							console.log(errorThrown); 
						
						}
					});
			
		}
		else {
			_self.toLogin();
		}
		
		
	};
	
	
	
	
	owner.listCase = function(pageNum,pageSize,callBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		_self = this;
		var listUrl = _self.SERVER_URL + "/appApi/case/list";
			
			jQuery.ajax(listUrl,{
						data: {
							"pageNum":pageNum,
							"pageSize":pageSize,
							"TOKEN"  :user.TOKEN,
							"LOGIN_NAME" : user.LOGIN_NAME
							
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(data);
//							var respData = JSON.parse(text); 
							if(data.result_code == -99 || data.result_code == -98){
								_self.toLogin();
							}
							else {
								callBack(data);
							}
							
						},
						error:function(xhr,type,errorThrown){  
					
						  
							errorCallBack();
						
						}
					});
		
	};
	
	owner.saveLogin = function(userInfo){
		localStorage.setItem('user', JSON.stringify(userInfo));
	};
	owner.getUserInfo = function(){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		return user;
	}
	owner.clearInfo = function(){
		localStorage.setItem('user', '{}');
	};
	
	
	owner.checkUpdate = function (version,isCheckLogin){
    	plus.nativeUI.showWaiting("加载中...");
    	var _self = this;
    	var checkUrl = _self.SERVER_URL + "/apkversion";
    	jQuery.ajax(checkUrl,{
						data: {
							VERSION:version
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						
						
						success:function(data){
//							plus.nativeUI.closeWaiting();
							console.log(data);
							if(data.result_code === 0){
								var btnArray = ['是', '否'];
								mui.confirm('检测到新版本，是否升级?', '检测到版本', btnArray, function(e) {
									if (e.index == 1) {
										console.log("index 1");
										if(isCheckLogin){
											_self.checkLogin();
										}
										
										
									} else {
										var resultData = data.result_data;
										var DOWN_URL = resultData.DOWN_URL + resultData.APK_NAME;
										console.log(resultData.DOWN_URL);
										
										var dtask = plus.downloader.createDownload( DOWN_URL, {}, function ( d, status ) {
										    if ( status == 200 ) { // 下载成功
										        var path = d.filename;
										        
										         plus.runtime.install(path);
										        console.log(d.filename);
										    } else {//下载失败
//										        alert( "Download failed: " + status ); 
										    }  
										});
										dtask.start(); 
//										plus.runtime.openURL(DOWN_URL);
										if(isCheckLogin){
											_self.checkLogin();
										}
										
									}
								});
							}
							else {
								if(isCheckLogin){
									_self.checkLogin();
								}
								else if(data.result_code === 1){
									plus.nativeUI.toast('已经是最新版本');
								}
								
							}
							
						},
						
						complete: function (xhr, TS) {
							plus.nativeUI.closeWaiting();
						},
						error:function(xhr,type,errorThrown){  
							if(isCheckLogin){
									_self.checkLogin();
							}
							else {
								plus.nativeUI.toast('版本检查失败');
							}
						  	
						
						}
					});
    	
    	
    	
	}
	owner.changeSend = function(caseCode,successCallBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		var _self = this;
    	var apiURL = _self.SERVER_URL + "/appApi/case/changeSend";
    	plus.nativeUI.showWaiting("加载中...");
    	jQuery.ajax(apiURL,{
						data: {
							CASE_CODE:caseCode,
							'LOGIN_NAME': user.LOGIN_NAME, 
							"TOKEN":user.TOKEN
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
//							plus.nativeUI.closeWaiting();
							console.log(data);
							if(data.result_code === 0){
								successCallBack(data);
							}
							else {
								errorCallBack(data);
							}
						},
						
						complete: function (xhr, TS) {
							plus.nativeUI.closeWaiting();
						},
						error:function(xhr,type,errorThrown){  
							var data = {
								message:"网络异常!"
							}
							errorCallBack(data);						
						}
					});
	}
	
	
	owner.getQueueCount = function(successCallBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		var _self = this;
    	var apiURL = _self.SERVER_URL + "/appApi/case/queueCount";
    
    	jQuery.ajax(apiURL,{
						data: {
							'LOGIN_NAME': user.LOGIN_NAME, 
							"TOKEN":user.TOKEN
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
//							plus.nativeUI.closeWaiting();
//							console.log(JSON.stringify(data));
							if(data.result_code === 0){
								successCallBack(data);
							}
							else {
								errorCallBack(data);
							}
						},
						
						error:function(xhr,type,errorThrown){  
							var data = {
								message:"网络异常!"
							}
							errorCallBack(data);						
						}
					});
	}
	
	
	owner.getAuditPush = function(successCallBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		var _self = this;
    	var apiURL = _self.SERVER_URL + "/appApi/case/auditPush";
        if(user &&user.LOGIN_NAME){
        	jQuery.ajax(apiURL,{
						data: {
							'LOGIN_NAME': user.LOGIN_NAME, 
							"TOKEN":user.TOKEN
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
//							plus.nativeUI.closeWaiting();
//							console.log(JSON.stringify(data));
							if(data.result_code === 0){
								successCallBack(data);
							}
							else {
								errorCallBack(data);
							}
						},
						
						error:function(xhr,type,errorThrown){  
							var data = {
								message:"网络异常!"
							}
							errorCallBack(data);						
						}
					});
        	
        }
    	
	}
	
	owner.listCaseForMsg = function(pageNum,pageSize,callBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		_self = this;
		var listUrl = _self.SERVER_URL + "/mobile/message/collectbyloginname";
			
			jQuery.ajax(listUrl,{
						data: {
							"pageNum":pageNum,
							"pageSize":pageSize,
							"TOKEN"  :user.TOKEN,
							"LOGIN_NAME" : user.LOGIN_NAME
							
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(JSON.stringify(data));
//							var respData = JSON.parse(text); 
							if(data.RESULT_CODE == -99 || data.RESULT_CODE == -98){
								_self.toLogin();
							}
							else {
								callBack(data);
							}
							
						},
						error:function(xhr,type,errorThrown){  
							console.log(JSON.stringify(errorThrown));
						  
							errorCallBack();
						
						}
					});
		
	};
	
	
	owner.getCaseMsg = function(caseCode,callBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		_self = this;
		var listUrl = _self.SERVER_URL + "/mobile/message/getmassage";
			
			jQuery.ajax(listUrl,{
						data: {
							"TOKEN"  :user.TOKEN,
							"LOGIN_NAME" : user.LOGIN_NAME,
							"CASE_CODE"  : caseCode
							
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(JSON.stringify(data));
//							var respData = JSON.parse(text); 
							if(data.RESULT_CODE == -99 || data.RESULT_CODE == -98){
								_self.toLogin();
							}
							else {
								callBack(data);
							}
							
						},
						error:function(xhr,type,errorThrown){  
					
						  
							errorCallBack();
						
						}
					});
		
	};
	
	
	owner.sendMsg = function(caseCode,msgCongent,callBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		_self = this;
		var listUrl = _self.SERVER_URL + "/mobile/message/insmassage";
			
			jQuery.ajax(listUrl,{
						data: {
							"TOKEN"  :user.TOKEN,
							"LOGIN_NAME" : user.LOGIN_NAME,
							"CASE_CODE"  : caseCode,
							"MESSAGE"    : msgCongent
							
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(JSON.stringify(data));
//							var respData = JSON.parse(text); 
							if(data.RESULT_CODE == -99 || data.RESULT_CODE == -98){
								_self.toLogin();
							}
							else {
								callBack(data);
							}
							
						},
						error:function(xhr,type,errorThrown){  
					
						  
							errorCallBack();
						
						}
					});
		
	};
	
	
	
	owner.getLastUnRead = function(caseCode,callBack,errorCallBack){
		var user = JSON.parse(localStorage.getItem('user') || '{}');
		_self = this;
		var listUrl = _self.SERVER_URL + "/mobile/message/getLastUnRead";
			
			jQuery.ajax(listUrl,{
						data: {
						
							"TOKEN"  :user.TOKEN,
							"LOGIN_NAME" : user.LOGIN_NAME,
							"CASE_CODE" :caseCode
							
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						processData:true,
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型 
						timeout:10000,//超时时间设置为10秒； 
						success:function(data){
							console.log(JSON.stringify(data));
//							var respData = JSON.parse(text); 
							if(data.RESULT_CODE == -99 || data.RESULT_CODE == -98){
								_self.toLogin();
							}
							else {
								callBack(data);
							}
							
						},
						error:function(xhr,type,errorThrown){  
							console.log(JSON.stringify(errorThrown));
						  
							errorCallBack();
						
						}
					});
		
	};
	
		
			
	
	
	
}(mui,$, window.app = {}));